package org.ade.monak.anak.service.gate.monak;

import java.util.List;

import org.ade.monak.anak.Variable.Status;
import org.ade.monak.anak.Variable.TipeKoneksi;
import org.ade.monak.anak.Variable.TipePesanMonak;
import org.ade.monak.anak.entity.Lokasi;
import org.ade.monak.anak.entity.Ortu;
import org.ade.monak.anak.service.DatabaseThreadService;
import org.ade.monak.anak.service.gate.SenderInternet;
import org.ade.monak.anak.service.gate.SenderSMS;
import org.ade.monak.anak.service.storage.DatabaseManagerAnak;
import org.ade.monak.anak.util.LokasisConverter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class SenderLogMonak{

	public SenderLogMonak(Context context, DatabaseThreadService databaseThread, Ortu ortu){
		this.ortu = ortu;
		this.context = context;
		this.senderInternet = new SenderInternet(context, new HandlerSenderInternetMonitoring(this));
		this.senderSMS = new SenderSMS(context, null);
		this.databaseThread	= databaseThread;
	}
	
	public void sendLogMonak(){
		databaseThread.addDatabaseThread(new Runnable() {
			public void run() {
				List<Lokasi> lokasis = getAllLogMonak();
				if(lokasis!=null){
					pesan = TipePesanMonak.RETRIEVE_LOG_LOCATION+","+ortu.getIdAnak()+","+LokasisConverter.convertLokasisToText(lokasis);
					senderInternet.kirimPesan(ortu.getIdOrtu(), pesan);	
				}		
			}
		});
		
	}
	
	private List<Lokasi> getAllLogMonak(){
		DatabaseManagerAnak db = new DatabaseManagerAnak(context);
		List<Lokasi> lokasis = db.getAllLogLokasi();
		return lokasis;
	}
	
	public void success(int tipeKoneksi) {
	}

	public void failed(int tipeKoneksi) {	
		if(tipeKoneksi==TipeKoneksi.INTERNET){
			senderSMS.kirimPesan(ortu.getNoHp(), pesan);
		}
	}
	
	private final SenderInternet senderInternet;
	private final SenderSMS			senderSMS;
	private final Ortu ortu;
	private final Context context;
	private String pesan;
	private final DatabaseThreadService databaseThread;
	

	private static final class HandlerSenderInternetMonitoring extends Handler{

		public HandlerSenderInternetMonitoring(SenderLogMonak senderMonitoring){
			this.senderMonitoring = senderMonitoring;
		}
		
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
				case Status.SUCCESS:{
					senderMonitoring.success(TipeKoneksi.INTERNET);
					break;
				}case Status.FAILED:{
					senderMonitoring.failed(TipeKoneksi.INTERNET);
					break;
				}
			}
		}
		private SenderLogMonak senderMonitoring;
		
	}

}
